<template>
  <div>
    <h1>IP定位信息</h1>
    <div v-if="locationData">
      <p><strong>IP 地址：</strong>{{ locationData.ip }}</p>
      <p><strong>城市：</strong>{{ locationData.city }}</p>
      <p><strong>地区：</strong>{{ locationData.province }}</p>
      <p><strong>位置：</strong>{{ locationData.city || '未知' }} {{ locationData.district || '未知' }}</p>
    </div>
    <div v-else>
      <p>加载中...</p>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, onMounted } from 'vue'
import axios from 'axios'

interface LocationData {
  ip: string
  city: string
  province: string
  district: string
}

export default defineComponent({
  name: 'IpLocator',
  setup() {
    // 存储定位数据
    const locationData = ref<LocationData | null>(null)
    
    // 获取定位数据的方法
const fetchLocationData = async () => {
  try {
    const ip = '124.127.222.50'  // 目标IP地址, 可替换为动态的用户IP
    const apiKey = 'be64c3933f21b1cf456735c678152f48' // 替换为你自己的高德API密钥
    const url = `https://restapi.amap.com/v3/ip?ip=${ip}&output=xml&key=${apiKey}`

    // 发送请求并打印响应数据
    const response = await axios.get(url)
    console.log('API Response:', response.data)

    // 检查返回的XML数据
    const parser = new DOMParser()
    const xmlDoc = parser.parseFromString(response.data, 'application/xml')

    // 输出解析后的 XML
    console.log('Parsed XML:', xmlDoc)

    // 解析 XML 数据
   if (xmlDoc.getElementsByTagName('parsererror').length > 0) {
  console.error('XML 解析错误');
} else {
  // 获取所需的数据
  const status = xmlDoc.getElementsByTagName('status')[0].textContent;
  const info = xmlDoc.getElementsByTagName('info')[0].textContent;
  const infocode = xmlDoc.getElementsByTagName('infocode')[0].textContent;
  const province = xmlDoc.getElementsByTagName('province')[0].textContent;
  const city = xmlDoc.getElementsByTagName('city')[0].textContent;
  const adcode = xmlDoc.getElementsByTagName('adcode')[0].textContent;
  const rectangle = xmlDoc.getElementsByTagName('rectangle')[0].textContent;

  // 打印提取的值
  console.log({
    status,
    info,
    infocode,
    province,
    city,
    adcode,
    rectangle
  });
}
  } catch (error) {
    console.error('定位请求失败:', error)
  }
}

    // 在组件挂载后获取数据
    onMounted(() => {
      fetchLocationData()
    })

    return {
      locationData
    }
  }
})
</script>

<style scoped>
h1 {
  font-size: 24px;
  margin-bottom: 20px;
}

p {
  font-size: 16px;
}
</style>
